﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;

namespace DataAccess_Layer
{
    public static class SanPhamDAC
    {
        public static List<ProductWithCatNameDTO> layDSSanPham()
        {
            return Product_DAC.getAllWithCatName();
        }

        public static List<MaSPMucNhapKhoSLTonDTO> layTTQLKho(string tenDangNhap)
        {
            List<MaSPMucNhapKhoSLTonDTO> rs = new List<MaSPMucNhapKhoSLTonDTO>();

            foreach (var sp in layDSSanPhamCuaNCC(tenDangNhap))
            {
                rs.Add(new MaSPMucNhapKhoSLTonDTO(sp.ID, sp.Total, sp.MinQuant));
            }

            return rs;
        }

        private static List<ProductWithCatNameDTO> layDSSanPhamCuaNCC(string tenDangNhap)
        {
            return layDSSanPham();
        }

        public static bool CapNhatSLTonSP(string tenDangNhap, long maSanPham, long soLuongTon)
        {
            DataAccessHelper dah = new DataAccessHelper();
            long soLuongTonCu = long.Parse(dah.ExecuteScalar("Select TotalQuantity From Product Where ID = @MaSanPham", "@MaSanPham", maSanPham).ToString());
            dah.close();

            if (soLuongTonCu != -1)
            {
                dah = new DataAccessHelper();
                int kq = dah.ExecuteNonQuery("Update Product Set TotalQuantity = @SoLuongTon Where ID = @MaSanPham and TotalQuantity <= MinQuant", "@SoLuongTon", soLuongTon, "@MaSanPham", maSanPham);
                if (kq == 1)
                {
                    dah.close();
                    dah = new DataAccessHelper();
                    string sql = "Insert Into LogAction(UpdateDate, UserName, UserType, TableName, OldData, NewData, UpdateType) Values(@UpdateDate, @UserName, @UserType, @TableName, @OldData, @NewData, @UpdateType)";
                    kq = dah.ExecuteNonQuery(sql, "@UpdateDate", DateTime.Now.ToString("yyyy/MM/dd"),
                        "@UserName", tenDangNhap,
                        "@UserType", "Supplier",
                        "@TableName", "Product.SoLuongTon",
                        "@OldData", soLuongTonCu.ToString(),
                        "@NewData", soLuongTon.ToString(),
                        "@UpdateType", "Update");
                }
                dah.close();
                return kq == 1;
            }

            return false;
        }
    }
}
